# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: meta_with.py 
@time: 2019/7/9 上午11:53
"""
'''
元类的上下文件管理器
利用@contextmanager装饰器实现with上下文管理
'''
import time
from contextlib import contextmanager

@contextmanager
def timethis(label):
    start = time.time()
    try:
        yield
    finally:
        end = time.time()
        print('{} : {}'.format(label, end - start))

# 增加事务上下文管理器
@contextmanager
def list_transaction(orig_list):
    working = list(orig_list)
    yield working
    orig_list[:] = working


# Example use
with timethis('counting'):
    n = 10000000
    while n > 0:
        n -= 1

# Example 2 use
items = [1, 2, 3]

with list_transaction(items) as working:
    working.append(4)

print(items)

'''
这段代码作用是任何对列表的修改只有当所有运行代码运行完成并且不出现异常的情况下才会生效。
给以下代码强制增加运行时错误导致该代码未完成运行。
'''
with list_transaction(items) as working:
    working.append(6)
    raise RuntimeError('oops')
    working.append(7)

print(items)